#
# openlookup/client/base.py
#
# Copyright 2009 Helsinki Institute for Information Technology
# and the authors.
#
# Authors: Ken Rimey <rimey@hiit.fi>
#

# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation files
# (the "Software"), to deal in the Software without restriction,
# including without limitation the rights to use, copy, modify, merge,
# publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

import random
import socket
from urlparse import urlsplit

ROOTS = ['http://any.openlookup.net:5851/',
         'http://lookup.infrahip.net:5851/',
         ]

class BaseProxy(object):
    def __init__(self, urls=None, preresolve=True):
        urls = urls or ROOTS
        if isinstance(urls, str):
            urls = [urls]
        self.addresses = map(parse_url, urls)
        self.preresolve = preresolve
        self._url = None

    @property
    def url(self):
        if self._url is None:
            self._url = self.choose_url()
        return self._url

    def reset(self):
        self._url = None

    def choose_url(self):
        if self.preresolve:
            addresses = self.resolve_addresses()
        else:
            addresses = self.addresses

        if not addresses:
            return None
        else:
            host, port = random.choice(addresses)
            return construct_url(host, port)

    def resolve_addresses(self):
        addrs = set()
        for host, port in self.addresses:
            try:
                for ip in socket.gethostbyname_ex(host)[2]:
                    addrs.add((ip, port))
            except socket.error:
                pass
        return list(addrs)

def parse_url(url):
    parts = urlsplit(url)
    if parts.scheme != 'http' or parts.path not in ('', '/'):
        raise ValueError('Bad base URL: %s' % url)
    return parts.hostname, parts.port

def construct_url(host, port=None):
    if port is None:
        return 'http://%s/' % host
    else:
        return 'http://%s:%s/' % (host, port)
